#include "config.h"
#include "isr.h"

#define SYSTICK
// #define EXTI
#define TIMER
#define UART

#ifdef SYSTICK
// SysTick interrupt handler - called every 1 ms (configured by SysConfig)
void SysTick_Handler(void)
{
	msTicks++;
}
#endif

#ifdef EXTI
/*
 * Group1 IRQ handler handles GPIOA interrupts among others.
 * SysConfig enabled PA7 (GPIOA pin 7) as falling edge interrupt.
 */
void GROUP1_IRQHandler(void)
{
	/* Check if GPIOA PA7 triggered (enabled interrupt status) */
	if (DL_GPIO_getEnabledInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN) & ENCODER_EC11_KEY_PIN)
	{
		/* Clear the interrupt flag for PA7 */
		DL_GPIO_clearInterruptStatus(ENCODER_PORT, ENCODER_EC11_KEY_PIN);
		/* Set a flag for the main loop or other tasks to process */
		encoderEvent = 1;
	}

	/* If other Group1 sources exist, optionally check/clear them here.
	 * DL_Interrupt_getStatusGroup and DL_Interrupt_clearGroup can be used
	 * for group-level handling if needed.
	 */
}

#endif

#ifdef TIMER

void TIMER_0_INST_IRQHandler(void)
{
	uint8_t raw[2];
	/* Check if TIER_0_INST update interrupt is pending */
	switch (DL_Timer_getPendingInterrupt(TIMER_0_INST))
	{
	case DL_TIMERG_IIDX_ZERO:
		/* code */
		// 原始按键读取：0 = 按下，1 = 释放
		raw[0] = (DL_GPIO_readPins(KEY_GRP_PORT, KEY_GRP_KEY_1_PIN) & KEY_GRP_KEY_1_PIN) ? 1 : 0;
		raw[1] = (DL_GPIO_readPins(KEY_GRP_PORT, KEY_GRP_KEY_2_PIN) & KEY_GRP_KEY_2_PIN) ? 1 : 0;
		// 8-bit 移位寄存器消抖（每1ms采样一次 8ms 为一个窗口）
		static uint8_t key_hist[2] = {0xFF, 0xFF};
		static uint8_t key_stable[2] = {1, 1}; // 1 表示稳定，初始状态为稳定释放

		key_hist[0] = (uint8_t)((key_hist[0] << 1) | raw[0]);

		if (key_hist[0] == 0x00 && key_stable[0] != 0) {
			key_stable[0] = 0;
			keyPressEvent[0] = 1; // 稳定按下事件
		} else if (key_hist[0] == 0xFF && key_stable[0] != 1) {
			key_stable[0] = 1;
			// 可设置释放事件（如需）
		}
		key_hist[1] = (uint8_t)((key_hist[1] << 1) | raw[1]);

		if (key_hist[1] == 0x00 && key_stable[1] != 0) {
			key_stable[1] = 0;
			keyPressEvent[1] = 1; // 稳定按下事件
		} else if (key_hist[1] == 0xFF && key_stable[1] != 1) {
			key_stable[1] = 1;
			// 可设置释放事件（如需）
		}

		break;
	
	default:
		break;
	}
}

#endif

#ifdef UART
void UART_0_INST_IRQHandler(void)
{
	// Check if RX interrupt is pending
	if (DL_UART_getPendingInterrupt(UART_0_INST) & DL_UART_IIDX_RX)
	{
		// Read the received byte
		uint8_t dat;
		dat = DL_UART_Main_receiveData(UART_0_INST);

		switch (uart_sm)
		{
		case 0:
		{
			if (dat == 'o')
				uart_sm = 1;
		}
		break;
		case 1:
		{
			if (dat == 'n')
			{
				uart_sm = 0;
				UART0_flag = 1;
			}
			else if (dat == 'f')
			{
				uart_sm = 2;
			}
			else
			{
				uart_sm = 0;
			}
		}
		break;
		case 2:
		{
			if (dat == 'f')
			{
				UART0_flag = 1;
			}
			uart_sm = 0; // 状态机归零
		}
		break;
		default:
			uart_sm = 0;
			break; // 状态机归零
		}
		// Clear RX interrupt flag
		DL_UART_Main_clearInterruptStatus(UART_0_INST, DL_UART_MAIN_INTERRUPT_RX);
	}
	// Optionally handle TX interrupt if implemented
}
#endif